<?php
header("Content-Type:text/html;charset=utf-8");
ob_start();
set_time_limit(0);
include ("../../nncms_manager_inc.php");
include $nncms_config_path . 'nn_cms_manager/controls/nncms_controls_public_function.php';
require_once $nncms_db_path . 'nns_log' . DIRECTORY_SEPARATOR . 'nns_db_op_log_class.php';
$log_inst = new nns_db_op_log_class();

$dc = nl_get_dc(array (
		'db_policy' => NL_DB_WRITE, 
		'cache_policy' => NP_KV_CACHE_TYPE_NULL
));
$dc->open();
$params = $_REQUEST;

$action = $params['action'];
unset($params['action']);
$log_params = (!empty($params) && is_array($params)) ? json_encode($params) : '';
$arr_file = pathinfo(__FILE__);
$base_file_name = $arr_file['basename'];
$base_file_name_base = substr($arr_file['filename'],0, -8);

include_once dirname(dirname(dirname(dirname(__FILE__)))) . '/nn_logic/full_assets/full_assets_site.class.php';


switch ($action)
{
    case "edit":
        $nns_id = $params['nns_id'];//key GUID
        unset($params['nns_id']);
        $result_unique = nl_full_assets_site::query_unique($dc, "where nns_siteid='{$params['nns_siteid']}' and nns_id !='{$nns_id}'");
        if($result_unique['ret'] != 0)
        {
            echo "<script>alert('" . $result_unique['reason'] . "');history.go(-1);</script>";
            break;
        }
        if(isset($result_unique['data_info']) && is_array($result_unique['data_info']) && !empty($result_unique['data_info']))
        {
            echo "<script>alert('nns_siteid已经存在,不允许在添加');history.go(-1);</script>";
            break;
        }
        $result = nl_full_assets_site::edit($dc, $params, $nns_id);
        if ($result['ret'])
        {
            echo "<script>alert('" . $result['reason'] . "');history.go(-1);</script>";
        }
        else
        {
            $log_inst->nns_db_op_log_add($_SESSION["nns_mgr_id"], $action, $_SESSION["nns_mgr_name"] . "修改:" . $log_params, $_SESSION["nns_manager_type"], $_SESSION["nns_org_id"]);
            echo "<script>alert('修改成功');</script>";
        }
        break;
    case "add":
        $result_unique = nl_full_assets_site::query_unique($dc, "where nns_siteid='{$params['nns_siteid']}'");
        if($result_unique['ret'] != 0)
        {
            echo "<script>alert('" . $result_unique['reason'] . "');history.go(-1);</script>";
            break;
        }
        if(isset($result_unique['data_info']) && is_array($result_unique['data_info']) && !empty($result_unique['data_info']))
        {
            echo "<script>alert('nns_siteid已经存在,不允许在添加');history.go(-1);</script>";
            break;
        }
        $arr_in_data = array(
            'nns_id'=>np_guid_rand(),
            'nns_siteid'=>$params['nns_siteid'],
            'nns_name'=>$params['nns_name'],
            'nns_state'=>$params['nns_state'],
            'nns_create_time'=>date("Y-m-d H:i:s"),
            'nns_modify_time'=>date("Y-m-d H:i:s"),
        );
        $result = nl_full_assets_site::add($dc, $arr_in_data);
        if ($result['ret'])
        {
            echo "<script>alert('" . $result['reason'] . "');</script>";
        }
        else
        {
            $log_inst->nns_db_op_log_add($_SESSION["nns_mgr_id"], $action, $_SESSION["nns_mgr_name"] . "添加:" . $log_params, $_SESSION["nns_manager_type"], $_SESSION["nns_org_id"]);
            echo "<script>alert('添加成功');</script>";
        }
        break;
    case "delete":
        $nns_ids = explode(",", $params['nns_id']);
        if(!is_array($nns_ids) || empty($nns_ids))
        {
            echo "<script>alert('删除成功,数据为空');</script>";
            break;
        }
        nl_full_assets_site::delete($dc,$nns_ids);
        $log_inst->nns_db_op_log_add($_SESSION["nns_mgr_id"], $action, $_SESSION["nns_mgr_name"] . "删除:" . $log_params, $_SESSION["nns_manager_type"], $_SESSION["nns_org_id"]);
        echo "<script>alert('删除成功');</script>";
        break;
    case "state":
        $nns_ids = explode(",", $params['nns_id']);
        if(!is_array($nns_ids) || empty($nns_ids))
        {
            echo "<script>alert('修改状态成功,数据为空');</script>";
            break;
        }
        $result = nl_full_assets_site::edit($dc, array('nns_state'=>$params['nns_state']), $nns_ids);
        if ($result['ret'])
        {
            echo "<script>alert('" . $result['reason'] . "');history.go(-1);</script>";
        }
        else
        {
            $log_inst->nns_db_op_log_add($_SESSION["nns_mgr_id"], $action, $_SESSION["nns_mgr_name"] . "修改:" . $log_params, $_SESSION["nns_manager_type"], $_SESSION["nns_org_id"]);
            echo "<script>alert('修改成功');</script>";
        }
        break;
    case "import":
        $verifyToken = md5('unique_salt' . $_POST['timestamp']);
        if(empty($_FILES) || !is_array($_FILES) || !isset($_FILES['vod_data_file']['tmp_name']))
        {
            echo "<script>alert('上传文件为空');history.go(-1);</script>";die;
        }
        $pathinfo = pathinfo($_FILES['vod_data_file']['name']);
        if(!isset($pathinfo['extension']) || strtolower($pathinfo['extension']) != 'csv')
        {
            echo "<script>alert('上传文件非CSV文件');history.go(-1);</script>";die;
        }
        if($_REQUEST['token'] != $verifyToken)
        {
            echo "<script>alert('token验证失效');history.go(-1);</script>";die;
        }
        ob_clean();
        $result = file_to_array($_FILES['vod_data_file']['tmp_name']);
        if($result === false)
        {
            echo "<script type=\"text/javascript\">alert(\"文件编码错误,请重新上传!\"); </script>";
            die;
        }
        if(empty($result) ||!is_array($result))
        {
            echo "<script>alert('无数据组装出来');history.go(-1);</script>";die;
        }
        $result = array_chunk($result,20,true);
        $temp_data = array();
        foreach ($result as $result_val)
        {
            $result_val_keys = array_keys($result_val);
            $result_unique = nl_full_assets_site::query_unique($dc,"where nns_siteid in('".implode("','", $result_val_keys)."')");
            if($result_unique['ret'] !=0)
            {
                echo "<script>alert('".$result_unique['reason']."');history.go(-1);</script>";die;
            }
            if(isset($result_unique['data_info']) && !empty($result_unique['data_info']) && is_array($result_unique['data_info']))
            {
                $result_unique = $result_unique['data_info'];
                foreach ($result_unique as $unique_val)
                {
                    if(isset($result_val[$unique_val['nns_siteid']]))
                    {
                        $temp_data[] = $result_val[$unique_val['nns_siteid']]['nns_name'];
                        unset($result_val[$unique_val['nns_siteid']]);
                    }
                }
            }
            if(empty($result_val) || !is_array($result_val))
            {
                continue;
            }
            $result_val = array_values($result_val);
            $result_add = nl_full_assets_site::add($dc, $result_val);
            if($result_add['ret'] !=0)
            {
                continue;
            }
        }
        $reason=(!empty($temp_data)) ? "成功，其中媒资[".implode("],[", $temp_data)."]已经注入" : 'OK';
        echo "<script>alert('".$reason."');history.go(-1);</script>";
        break;
    default:
        echo "<script>alert('没有此方式');</script>";
        break;
}
$partner_inst = null;
$log_inst = null;
echo "<script>self.location='".$base_file_name_base."_list.php?model_id={$params['nns_model_id']}';</script>";

function file_to_array($upload_file)
{
    $date = date('Y-m-d H:i:s');
	$upload_file = fopen($upload_file, 'r');
	$i=0;
	$data = $header_array = array();
	setlocale(LC_ALL, 'zh_CN');
	while (!feof($upload_file))
	{
	    $line_arr = fgetcsv($upload_file);
		if(!is_array($line_arr) || empty($line_arr))
		{
		    continue;
		}
// 		$temp_data = array();
// 		foreach ($line_arr as $temp_key=>$temp_val)
// 		{
// 		    $temp_val = trim($temp_val);
// 		    if(strlen($temp_val) <1)
// 		    {
// 		        $temp_data[$temp_key]='';
// 		        continue;
// 		    }
//             $temp_data[$temp_key] = iconv(mb_detect_encoding($temp_val),'UTF-8',$temp_val) ;
// 		}
// 		$line_arr = $temp_data;
		if($i<1)
		{
		    $i++;
		    continue;
		}
		if (is_array($line_arr) && !empty($line_arr) && $i>0)
		{
			$nns_siteid = isset($line_arr[0]) ? trim($line_arr[0]) : '';
			$nns_name = isset($line_arr[1]) ? trim($line_arr[1]) : '';
			if(strlen($nns_name) <1 || strlen($nns_siteid) <1)
			{
			    continue;
			}
			$data[$nns_siteid] = array(
                'nns_id'=>np_guid_rand(),
                'nns_siteid'=>$nns_siteid,
                'nns_name'=>$nns_name,
                'nns_state'=>0,
                'nns_create_time'=>date("Y-m-d H:i:s"),
                'nns_modify_time'=>date("Y-m-d H:i:s"),
			);
		}
		$i++;
	}
	fclose($upload_file);
	return $data;
}